package com.example.smartcity.ui.person.login

import android.content.Context
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.example.smartcity.databinding.ActivityLoginBinding
import com.example.smartcity.logic.net_work.Response.getLogin
import com.example.smartcity.logic.net_work.Response.getRegister
import com.example.smartcity.logic.utils.BaseActivity
import com.example.smartcity.logic.utils.Toast.Companion.showToast
import com.example.smartcity.ui.home.HomeViewModel
import kotlinx.coroutines.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import org.json.JSONObject

/**
 * 登录界面
 */
class LoginActivity : BaseActivity() {
    private lateinit var mBinding: ActivityLoginBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        // 登录
        mBinding.personBtnOk.setOnClickListener {
            setUserLogin()
        }

        // 注册
        mBinding.personBtnOkAdd.setOnClickListener {
            setUserLoginAdd()
        }

        // 处理点击事件
        tvOnCLick()
    }

    /**
     * 用户注册
     */
    @OptIn(DelicateCoroutinesApi::class)
    private fun setUserLoginAdd() {
        // 获取填写好的信息
        val userName = mBinding.personUserNameAdd
        val userPwd = mBinding.personUserPwdAdd
        val userPhone = mBinding.personUserPhoneAdd
        val userNickName = mBinding.personUsernickNameAdd


        GlobalScope.launch {
            val map = JSONObject().apply {
                put("userName", userName.text.toString())
                put("nickName", userNickName.text.toString())
                put("password", userPwd.text.toString())
                put("phonenumber", userPhone.text.toString())
            }

            if (userName.text.isEmpty() && userPwd.text.isEmpty() && userPhone.text.isEmpty()){
                runOnUiThread {
                    "不能为空".showToast()
                }
            }else {
                // 发起网络请求
                val a = getRegister(RequestBody.create("application/json".toMediaType(), map.toString()))

                // 打印信息
                runOnUiThread {
                    if(a.code == 500){
                        "aaa ${a.msg}".showToast()
                    }
                }

                if (a.code == 200){
                    runOnUiThread {
                        "注册成功！ 正在前往登录页面。".showToast()
                    }
                    withContext(Dispatchers.IO) {
                        Thread.sleep(1000)
                    }
                    // 切换登录模式
                    runOnUiThread {
                        mBinding.loginAdd.visibility = View.GONE
                        mBinding.login.visibility = View.VISIBLE

                        // 填充数据给登录界面
                        mBinding.personUserName.text = userName.text
                        mBinding.personUserPwd.text = userPwd.text
                    }
                }
            }



        }

    }


    /**
     * 登录和注册点击事件切换
     */
    private fun tvOnCLick() {
        // 返回登录
        mBinding.personOkAdd.setOnClickListener {
            runOnUiThread {
                mBinding.loginAdd.visibility = View.GONE
                mBinding.login.visibility = View.VISIBLE

            }
        }

        // 注册
        mBinding.personNo.setOnClickListener {
            runOnUiThread {
                mBinding.login.visibility = View.GONE
                mBinding.loginAdd.visibility = View.VISIBLE
            }
        }
    }


    /**
     * 用户登录
     */
    @OptIn(DelicateCoroutinesApi::class)
    private fun setUserLogin() {
        // 获取输入账号
        val userName = mBinding.personUserName
        // 获取输入密码
        val userPasswd = mBinding.personUserPwd

        // 判断输入框是否为空
        if(userName.text.isEmpty() || userPasswd.text.isEmpty()){
            "用户名或密码不能为空！".showToast()
        } else if(userPasswd.text.length < 3) {
            "密码不能少于6位数！".showToast()
        }

        // 发起网络请求
        GlobalScope.launch {
            getLogin(RequestBody.create("application/json".toMediaType(), JSONObject().apply {
                this.put("username", userName.text)
                this.put("password", userPasswd.text)
            }.toString())).run {
                runOnUiThread {
                    if(this.code == 200){
                        val edit = getSharedPreferences("token", Context.MODE_PRIVATE).edit()
                        edit.putString("token", this.token)
                        edit.putBoolean("user", true)
                        edit.apply()
                        // 存储好token销毁登录页面
                        this@LoginActivity.finish()
                    }else this.msg.showToast() // 提示

                }
            }
        }
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // 销毁意图
        this.finish()
        return super.onOptionsItemSelected(item)
    }
}